<?php
/**
 *
 *
 * LICENSE:
 *
 * @category   Zend
 * @package    Zend_Easthv
 * @copyright  Copyright (c) 2009-2010 Easthv Team @ East Hui Van Business Consulting Co., Ltd.(http://www.easthv.com)
 * @license    http://framework.zend.com/license/   BSD License
 * @version    1.0
 * @link       http://www.easthv.com
 * @since      1.0
*/

/**
 * Class for Unique Validation
 *
 * @category   Zend
 * @package    Zend_Easthv
 * @uses       Zend_Validate_Abstract
 * @copyright  Copyright (c) 2009-2010 Easthv Team @ East Hui Van Business Consulting Co., Ltd.(http://www.easthv.com)
 * @license    http://framework.zend.com/license/   BSD License
 * @version    1.0
 * @link       http://www.easthv.com
 * @since      1.0
 * @deprecated
 */
class Zend_Validate_Unique extends Zend_Validate_Abstract 
{ 
    /** 
     * @var string 
     */ 
    const NOT_UNIQUE = "notUnique"; 

    /** 
     * @var array
     */
    protected $_param;

    /** 
     * @var array
     */
    protected $_excetion;
 
    /** 
     * @var array 
     */ 
    protected $_messageTemplates = array(
        self::NOT_UNIQUE => "Input value has been taken."
    ); 

    /** 
     * Sets validator options 
     * 
     * @param  string $param
     * @return void 
     */
    public function __construct($param, $exception = null)
    {
        $this->_param = $param;
        $this->_excetion = $exception;
    }

    /** 
     * Defined by Zend_Validate_Interface 
     * 
     * Returns true if and only if the input value is unique in database table
     * 
     * @param string $value
     *
     * @return boolean 
     */ 
    public function isValid($value) 
    {
        $param = $this->_param;

        if (!is_array($param) || !$param['model'] || !$param['field']) {
            throw new Exception("Incorrect input of Unique Validation");
        }

        // Set the value 
        $value = (string) $value; 
        $this->_setValue($value);

        $modelName = "Easthv_Model_" . $param['model'];
        
        $model = new $modelName;

        $where = array(array("{$param['field']} = ?" , $value));
        $result = array();
        if ($this->_excetion && is_array($this->_excetion)) {

            $where[] = $this->_excetion;
            $result = $model->find("count",array(
                'where' => $where
            ));
        
        } else {
        
            $result = $model->find("count",array(
                'where' => $where
            ));
        
        }

        if (!$result) {
            return true;
        }
        
        $this->_error(self::NOT_UNIQUE);
        return false;
    } 

} 
